"use client"
import React, {useState} from "react";
import { Form, Input, InputNumber, message, Modal, Button, Space, Alert } from "antd";
import { aiGenerateQuestionsUsingPost } from "@/api/questionController";

interface Props {
    visible: boolean;
    onSubmit: () => void;
    onCancel: () => void;
}

/**
 * AI 生成题目弹窗
 * - 支持选择题型与数量
 * - 提交后调用后端接口生成题目与题解
 */
const AIGenerateModal: React.FC<Props> = (props) => {
    const { visible, onSubmit, onCancel } = props;
    const [form] = Form.useForm<API.QuestionAIGenerateRequest>();
    const [ loading , setLoading ]=useState(false);

    /**
     * 提交处理函数：调用 AI 生成接口
     */
    const doSubmit = async (values: API.QuestionAIGenerateRequest) => {
        // 统一的加载提示
        const hide = message.loading("正在生成题目与题解，请稍候...");
        setLoading(true);
        try {
            // 调用后端 AI 生成接口
            const res = await aiGenerateQuestionsUsingPost({
                number: values.number,
                questionType: values.questionType,
            });
            // 判断业务状态码
            if (res?.code === 0) {
                message.success("生成题目已提交，稍后自动刷新");
                onSubmit?.();
            } else {
                message.error(`生成失败：${res?.message ?? "请稍后重试"}`);
            }
        } catch (error: any) {
            message.error("生成失败，" + error.message);
        } finally {
            hide();
        }
        setLoading(false);
    };

    return (
        <Modal
            destroyOnClose
            title={"AI 生成题目"}
            open={visible}
            footer={null}
            onCancel={() => onCancel?.()}
        >
            <Space direction="vertical" size={16} style={{ width: "100%" }}>
                <Alert
                    message="说明"
                    description="输入题目的大方向并输入需要生成的数量，系统会自动生成题目与题解。生成完成后，列表会自动刷新。"
                    type="info"
                    showIcon
                />
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{ number: 5 }}
                    onFinish={doSubmit}
                >
                    <Form.Item
                        label="题目方向"
                        name="questionType"
                    >
                        <Input placeholder="比如JavaScript"></Input>
                    </Form.Item>
                    <Form.Item
                        label="生成数量"
                        name="number"
                        rules={[
                            { required: true, message: "请输入数量" },
                            {
                                validator: (_, value) => {
                                    if (typeof value !== "number") return Promise.reject("数量必须为数字");
                                    if (value < 1 || value > 10) return Promise.reject("数量范围为 1-10");
                                    return Promise.resolve();
                                },
                            },
                        ]}
                    >
                        <InputNumber min={1} max={50} precision={0} style={{ width: "100%" }} placeholder="请输入生成数量（1-10）" />
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button onClick={() => onCancel?.()}>取消</Button>
                            <Button loading={loading} type="primary" htmlType="submit">
                                开始生成
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Space>
        </Modal>
    );
};

export default AIGenerateModal;
